package com.sites.cms.permission;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import com.jfinal.aop.Aop;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.TemplateException;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import com.sites.common.SiteInfo;
import com.sites.common.model.Account;

/**
 * 菜单列表或按钮组的权限控制，指定多个actionKey中的公共部分即可
 * 
 * 用例一：
 * #pld("/cmsRole/")
 * 		<a href="/cmsRole/addRole"></a>
 * 		<a href="/cmsRole/delRole"></a>
 * #end
 * 
 * 用例二：
 * #pld("/cmsRole/","/cmsAcount/")
 * 		<a href="/cmsRole/addRole"></a>
 * 		<a href="/cmsRole/delRole"></a>
 * 		<a href="/cmsAcount/addAccount"></a>
 * #end
 * 
 * @author zyg
 * 2020年1月30日 下午10:35:38
 */
public class PermissionListDirective extends Directive {

	private PermissionService permSrv = Aop.get(PermissionService.class);
	
	@Override
	public void exec(Env env, Scope scope, Writer writer) {
		List<String> actionList = getActionList(scope);
		HttpSession session = (HttpSession) scope.get("session");
		if(session != null){
			Account account = (Account) session.getAttribute(SiteInfo.account);
			boolean flag = hasListPerm(actionList, account);
			if(flag){
				stat.exec(env, scope, writer);
			}					
		}

	}
	
	@Override
	public boolean hasEnd() {
		return true;
	}
	
	private List<String> getActionList(Scope scope){
		List<String> actionList = new ArrayList<String>();
		Object[] valueObjects = exprList.evalExprList(scope);
		if(valueObjects.length <= 0){
			throw new TemplateException("The parameters of #pld directive must >= 1", location);
		}
		for (int i=0; i<valueObjects.length; i++) {
			if (valueObjects[i] instanceof String) {
				actionList.add((String)valueObjects[i]);
			} else {
				throw new TemplateException("The parameter string of #pld directive must be String type", location);
			}
		}
		return actionList;
	}
	
	private boolean hasListPerm(List<String> actionList, Account account){
		boolean flag = false;
		
		if(account != null){
			if(SiteInfo.adminName.equals(account.getUserName())){
				flag = true;
			}
			if(!flag){
				flag = permSrv.hasListPerm(actionList, account.getId());
			}
		}
		
		return flag;
	}

}
